package com.example.app.utils;

import org.springframework.core.io.ClassPathResource;

import java.io.DataInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by wangtao on 2018/3/2.
 */
public class KeyHelper {
    /**
     * 解析公钥
     * @param fileName
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String fileName) throws Exception{
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream in = classPathResource.getInputStream();
        DataInputStream dis = new DataInputStream(in);
        byte[] keyBytes = new byte[(int)in.available()];
        dis.readFully(keyBytes);
        dis.close();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
}
